// pages/userEvaluation/userEvaluation.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    score:5,
    imageUrl:'',
    imagesList: [],
    evaluationContext:'',
    isJingxuan:false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var productId = options.productid;
    var opId = options.opid;
    that.setData({
      productid: productId,
      opId:opId
    });
    //获取手机高度
    that.setData({
      navH: app.globalData.navHeight
    });
    wx.request({
      url: app.globalData.url + 'getProductById',
      data:{"productId":productId},
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      success: function (res) {
        that.setData({
          product:res.data.data,
        });
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  jingxuan:function(){
    var that = this;
    var flag = that.data.isJingxuan;
    that.setData({
      isJingxuan:!flag,
    })
  },

  submit: function(){
    var that = this;
    if (that.data.evaluationContext.trim() == ''){
      wx.showToast({
        title: '请填写描述后发表哦！',
        icon: 'none'
      });
      return;
    }
    var imageUrls = '';
    for(var i = 0; i < that.data.imagesList.length; i++){
      imageUrls = imageUrls + that.data.imagesList[i] + ";;;";
    }

    // wx.request({
    //   url: app.globalData.url + 'getUserOrderList',
    //   method: 'GET',
    //   data: {
    //     userId: wx.getStorageSync("userId"),
    //     type: that.data.type
    //   },
    //   success: function (res) {
    //     if (that.data.type == 4) {
    //       that.setData({
    //         orderPasList: res.data.data
    //       })
    //     } else {
    //       that.setData({
    //         orderList: res.data.data
    //       });
    //     }
    //   },
    // });
    wx.request({
      url: app.globalData.url + 'saveUserEvaluation',
      data:{
        opId: that.data.opId,
        productId:that.data.productid,
        evaluation:that.data.evaluationContext,
        images:imageUrls,
        level:that.data.score,
        userId: wx.getStorageSync("userId"),
        flag: that.data.isJingxuan,
      },

      method: 'post',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res){
        if(res.data.result == 1){
          wx.showToast({
            title: '发表成功！',
            icon: 'success'
          });
          setTimeout(function () {
            wx.navigateTo({
              url: '/pages/evaluationSuccess/evaluationSuccess?productid=' + that.data.productid,
            })
          }, 1500)
        } else {
          console.log(111)
          wx.showToast({
            title: res.data.errmsg,
            icon: 'failed'
          });
        }
      }
    });
  },

  changeScore:function(e){
    var that = this;
    var currentScore = e.target.dataset.score;
    that.setData({
      score:currentScore,
    });
  },

  setContext:function(e){
    var that = this;
    var currentContext = that.utf16toEntities(e.detail.value);

    that.setData({
      evaluationContext: currentContext,
    });
  },
  utf16toEntities: function(str){
    var patt = /[\ud800-\udbff][\udc00-\udfff]/g
    return str.replace(patt, function (char) {
      var H, L, code;
      if (char.length === 2) {
        H = char.charCodeAt(0); // 取出高位  
        L = char.charCodeAt(1); // 取出低位  
        code = (H - 0xD800) * 0x400 + 0x10000 + L - 0xDC00;  
        return "&#" + code + ";";
      } else {
        return char;
      }
    })
  },

  addPic: function () {
    var that = this;
    if (that.data.imagesList.length >= 6){
      wx.showToast({
        title: '最多上传6张图片！',
        icon: "none",
      });
      return;
    }
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        //const imagesList = that.data.imagesList.concat(tempFilePaths);
        //启动上传等待中...  
        setTimeout(() => {
          wx.showLoading({
            title: '正在上传...',
            icon: 'loading'
          });
          var filetype = tempFilePaths[0].split(".");
          wx.uploadFile({

            url: app.globalData.url + 'uploadFile',
            filePath: tempFilePaths[0],
            name: 'files',
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            formData: {
              'filetype': 0,
              "filesFileName": "qqq." + filetype[filetype.length - 1]
            },
            success(res) {
              wx.hideLoading();
              var data = JSON.parse(res.data);
              if (data.result == 1) {
                that.setData({
                  imageUrl: data.data,
                })
              }
              var list = that.data.imagesList;
              list.push(that.data.imageUrl);
              that.setData({
                imagesList: list
              });

              wx.showToast({
                title: '上传成功',
                icon: null,
              });
            },
            fail: function () {
              wx.hideLoading();
            }
          });
        }, 500);
      },
      fail: function (res) {
        wx.hideLoading();
      }
    })
  },

  deleteImg:function(e){
    var that = this;
    var index = e.target.dataset.index;
    var list = that.data.imagesList;
    wx.showModal({
      title: '提示',
      content: '确定要删除该图片吗？',
      success: function (sm) {
        if (sm.confirm) {
          list.splice(index,1);
          that.setData({
            imagesList:list,
          });
        } else if (sm.cancel) {

        }
      }
    })
  },

  navBack: function () {
    wx.navigateBack({

    })
  }
})